package wwj.dao;

import wwj.bean.User;
import wwj.utils.SqlUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {


    public User checkUser(User user){
        Connection conn = SqlUtil.getConnection();
        if(conn==null){
            user.setId(-1);
            return user;
        }
        String sql="select * from users where usr=? and pwd=?";
        PreparedStatement ps;
        try{
            ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUsr());
            ps.setString(2,user.getPwd());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                user.setId(rs.getInt("id"));
                user.setEmail(rs.getString("email"));
                user.setSex(rs.getString("sex"));
                user.setTel(rs.getString("tel"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            user.setId(-1);
        }
        return user;
    }

    //用户注册方法
    public String insertUser(User user) {
        String sql_status=null;
        int success_line = 0;
        Connection conn = SqlUtil.getConnection();
        if(conn==null){
            sql_status = "系统错误";
            return sql_status;
        }
        System.out.println("输入的数据："+user);
        String sql= "insert into users(tel,usr,email,pwd,sex) values(?,?,?,?,?)";
        PreparedStatement ps;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getTel());
            ps.setString(2,user.getUsr());
            ps.setString(3,user.getEmail());
            ps.setString(4,user.getPwd());
            ps.setString(5,user.getSex());
            success_line = ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
            sql_status = "系统错误";
        }
        if (success_line!=0){
            sql_status="注册成功";
        }
        return sql_status;
    }
    //检查用户账户存在方法
    public boolean selectByUsername(String usr){
        boolean flag = true;
        String sql="select * from users where usr = ?";
        Connection conn= SqlUtil.getConnection();
        if(conn==null){
            return false;
        }
        PreparedStatement ps;
        try{
             ps = conn.prepareStatement(sql);
             ps.setString(1,usr);
             ResultSet rs = ps.executeQuery();
             while (rs.next()){
                 flag = false;
                 break;
             }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }
}
